<?php


namespace App\Common\Logging\Injection;


use Illuminate\Log\Events\MessageLogged;
use Illuminate\Support\Facades\Mail;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;

/**
 * 注入到log引擎，监听日志发送数据到email，实时发送
 * Class LoggerInjection
 * @package App\Common\Logging\Injection
 */
class LoggerPushEmailInjection
{
    public function __invoke($logger)
    {
        try {
            //此处用添加监听事件 可以添加多个事件
            $logger->listen(function (MessageLogged $messageLogged){
                $to = env('LOG_PUSH_TO_EMAIL', "");
                if (!IsEmail($to)) {
                    return false;
                }

                if (!env('MAIL_USERNAME', '') || !env('MAIL_PASSWORD', '')) {
                    die(ApiReturn(RETURN_CHECK_PARAMS_FAIL, "If you need to use push log to mailbox, you must configure mailbox information first."));
                }

                $appName = env("APP_NAME", "Scarecrow Log Engine") . '[' . env("APP_ENV", "development") . ']';
                $subject = $appName . "[" . strtoupper($messageLogged->level) . "]: " . mb_substr($messageLogged->message, 0, 20) . (mb_strlen($messageLogged->message) > 20 ? "..." : "");
                $allLevel = env('LOG_PUSH_EMAIL_LEVEL', '');
                $allLevel && $allLevel = explode(',', $allLevel);
                if (!$allLevel) {
                    $allLevel = ['error'];
                } else {
                    array_walk($allLevel, function (&$item) {
                        $item = strtolower($item);
                    });
                }

                if (in_array(strtolower($messageLogged->level), $allLevel)) {
                    Mail::html($this->createFormData($messageLogged), function($msg) use ($to, $subject){
                        $msg->to($to)->subject($subject);
                    });
                }
                return true;
            });
        } catch (\Exception $e) {

        }
    }

    /**
     * 生成错误表单
     * @param $data
     * @return string
     */
    protected function createFormData($data) {
        $content = "<tr><td style='width: 50%;border:1px solid black;'>AppName</td><td style='width: 50%;border:1px solid black;'>". env("APP_NAME", "Scarecrow Log Engine") ."</td></tr>";
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>AppEnv</td><td style='width: 50%;border:1px solid black;'>". env("APP_ENV", "development") ."</td></tr>";
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>Level</td><td style='width: 50%;border:1px solid black;'>{$data->level}</td></tr>";
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>Message</td><td style='width: 50%;border:1px solid black;'>{$data->message}</td></tr>";
        foreach ($data->context as $key => $item) {
            $content .= "<tr><td style='width: 50%;border:1px solid black;'>Content-{$key}</td><td style='width: 50%;border:1px solid black;'>{$item}</td></tr>";
        }
        $content .= "<tr><td style='width: 50%;border:1px solid black;'>Create Time</td><td style='width: 50%;border:1px solid black;'>". date("Y-m-d H:i:s") ."</td></tr>";

        $html = "<html><body style='width: 100%;'><table style='width: 100%;border:1px solid black;text-align: center;' cellspacing='0' cellpadding='0'>{$content}</table></body></html>";
        return $html;
    }
}